package com.crm.business.crm.controller;


import com.crm.business.crm.log.CrmLeadsLog;
import com.crm.business.crm.service.CrmUploadExcelService;
import com.crm.business.crm.service.ICrmLeadsService;
import com.crm.common.crm.common.CrmModel;
import com.crm.common.crm.constant.CrmCodeEnum;
import com.crm.common.crm.constant.CrmEnum;
import com.crm.common.crm.constant.FieldEnum;
import com.crm.common.crm.entity.BO.*;
import com.crm.common.crm.entity.PO.CrmField;
import com.crm.common.crm.entity.PO.CrmLeads;
import com.crm.common.crm.entity.PO.CrmTmkLeads;
import com.crm.common.crm.entity.VO.CrmDataCheckVO;
import com.crm.common.crm.entity.VO.CrmInfoNumVO;
import com.crm.common.crm.entity.VO.CrmLeadsTransferCustomer;
import com.crm.common.crm.entity.VO.CrmModelFiledVO;
import com.crm.common.ka.core.common.R;
import com.crm.common.ka.core.common.Result;
import com.crm.common.ka.core.common.SubModelType;
import com.crm.common.ka.core.common.log.BehaviorEnum;
import com.crm.common.ka.core.common.log.SysLog;
import com.crm.common.ka.core.common.log.SysLogHandler;
import com.crm.common.ka.core.entity.BasePage;
import com.crm.common.ka.core.exception.CrmException;
import com.crm.common.crm.entity.BO.CrmSearchBO;
import com.crm.common.ka.core.servlet.upload.FileEntity;
import com.crm.business.utils.UserUtil;
import com.crm.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 线索表 前端控制器
 * </p>
 *
 * @author zhangzhiwei
 * @since 2020-05-21
 */
@RestController
@RequestMapping("/crmLeads")
@Api(tags = "线索模块接口")
@SysLog(subModel = SubModelType.CRM_LEADS,logClass = CrmLeadsLog.class)
public class CrmLeadsController {

    @Autowired
    private ICrmLeadsService crmLeadsService;

    @Autowired
    private CrmUploadExcelService uploadExcelService;

    @PostMapping("/queryById/{leadsId}")
    @ApiOperation("根据ID查询")
    public Result<CrmModel> queryById(@PathVariable("leadsId") @ApiParam(name = "id", value = "id") Integer leadsId) {
        Integer number = crmLeadsService.lambdaQuery().eq(CrmLeads::getLeadsId, leadsId).count();
        if (number == 0) {
            throw new CrmException(CrmCodeEnum.CRM_DATA_DELETED, "线索");
        }
        CrmModel model = crmLeadsService.queryById(leadsId);
        return R.ok(model);
    }

    @PostMapping("/deleteByIds")
    @ApiOperation("根据ID删除数据")
    @SysLogHandler(behavior = BehaviorEnum.DELETE)
    public Result deleteByIds(@ApiParam(name = "ids", value = "id列表") @RequestBody List<Integer> ids) {
        crmLeadsService.deleteByIds(ids);
        return R.ok();
    }

    @PostMapping("/transfer")
    @ApiOperation("线索转客户功能")
    @SysLogHandler(behavior = BehaviorEnum.TRANSFER)
    public Result transfer(@ApiParam(name = "ids", value = "id列表") @RequestBody CrmLeadsTransferCustomer crmLeadsTransferCustomer) {
        crmLeadsService.transfer(crmLeadsTransferCustomer);
        return R.ok();
    }

    @PostMapping("/revokeTransfer")
    @ApiOperation("线索撤销转化")
    @SysLogHandler(behavior = BehaviorEnum.REVOKETRANSFER)
    public Result revokeTransfer(@ApiParam(name = "ids", value = "id列表") @RequestBody CrmLeadsTransferCustomer crmLeadsTransferCustomer) {
        crmLeadsService.revokeTransfer(crmLeadsTransferCustomer);
        return R.ok();
    }

    @PostMapping("/queryLeadsFieldForTraining")
    public Result queryLeadsFieldForTraining(){
        return R.ok(crmLeadsService.queryLeadsFieldForTraining());
    }


    @PostMapping("/downloadExcel")
    @ApiOperation("下载导入模板")
    public void downloadExcel(HttpServletResponse response) throws IOException {
        crmLeadsService.downloadExcel(response);
    }

    @PostMapping("/allExportExcel")
    @ApiOperation("全部导出")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_EXPORT, object = "线索导出", detail = "全部导出")
    public void allExportExcel(@RequestBody CrmSearchBO search, HttpServletResponse response) {
        search.setPageType(0);
        List<Integer> list = UserUtil.getUser().getRoles();
        Integer superRole = UserUtil.getSuperRole();
        boolean b = list.contains(superRole);
        if (b){
            search.setPageType(10000);
        }
        crmLeadsService.exportExcel(response, search);
    }

    @PostMapping("/batchExportExcel")
    @ApiOperation("选中导出")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_EXPORT, object = "线索导出", detail = "选中导出")
    public void batchExportExcel(@RequestBody @ApiParam(name = "ids", value = "id列表") List<Integer> ids, HttpServletResponse response) {
        CrmSearchBO search = new CrmSearchBO();
        search.setPageType(0);
        Integer superRole = UserUtil.getSuperRole();
        List<Integer> list = UserUtil.getUser().getRoles();
        boolean b = list.contains(superRole);
        if (b){
            search.setPageType(10000);
        }
        search.setLabel(CrmEnum.LEADS.getType());
        CrmSearchBO.Search entity = new CrmSearchBO.Search();
        entity.setFormType(FieldEnum.TEXT.getFormType());
        entity.setSearchEnum(CrmSearchBO.FieldSearchEnum.ID);
        entity.setValues(ids.stream().map(Object::toString).collect(Collectors.toList()));
        search.getSearchList().add(entity);
        search.setPageType(0);
        if (b){
            search.setPageType(10000);
        }
        crmLeadsService.exportExcel(response, search);
    }

    @PostMapping("/queryPageList")
    @ApiOperation("查询列表页数据")
    public Result<BasePage<Map<String, Object>>> queryPageList(@RequestBody CrmSearchBO search) {
        BasePage<Map<String, Object>> mapBasePage = crmLeadsService.queryPageList(search);
        return R.ok(mapBasePage);
    }

    @PostMapping("/changeOwnerUser")
    @ApiOperation("修改线索负责人")
    @SysLogHandler(behavior = BehaviorEnum.CHANGE_OWNER)
    public Result changeOwnerUser(@RequestBody CrmChangeOwnerUserBO crmChangeOwnerUserBO) {
        crmLeadsService.changeOwnerUser(crmChangeOwnerUserBO.getIds(), crmChangeOwnerUserBO.getOwnerUserId(), crmChangeOwnerUserBO.getLeadsUserId());
        return R.ok();
    }

    @PostMapping("/field")
    @ApiOperation("查询新增所需字段")
    public Result<List<CrmModelFiledVO>> queryField() {
        List<CrmModelFiledVO> crmModelFiledList = crmLeadsService.queryField(null);
        return R.ok(crmModelFiledList);
    }

    @PostMapping("/field/{id}")
    @ApiOperation("查询修改数据所需信息")
    public Result<List<CrmModelFiledVO>> queryField(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<CrmModelFiledVO> crmModelFiledList = crmLeadsService.queryField(id);
        return R.ok(crmModelFiledList);
    }

    @PostMapping("/add")
    @ApiOperation("保存数据")
    @SysLogHandler(behavior = BehaviorEnum.SAVE,object = "#crmModel.entity[leadsName]",detail = "'新增了线索:' + #crmModel.entity[leadsName]")
    public Result add(@RequestBody CrmModelSaveBO crmModel) {
        crmLeadsService.addOrUpdate(crmModel,false);
        return R.ok();
    }

    @PostMapping("/update")
    @ApiOperation("修改数据")
    @SysLogHandler(behavior = BehaviorEnum.UPDATE)
    public Result update(@RequestBody CrmModelSaveBO crmModel) {
        crmLeadsService.addOrUpdate(crmModel,false);
        return R.ok();
    }

    @PostMapping("/queryFileList")
    @ApiOperation("查询附件列表")
    public Result<List<FileEntity>> queryFileList(@RequestParam("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<FileEntity> fileEntities = crmLeadsService.queryFileList(id);
        return R.ok(fileEntities);
    }

    @PostMapping("/num")
    @ApiOperation("详情页数量展示")
    public Result<CrmInfoNumVO> num(@RequestParam("id") @ApiParam(name = "id", value = "id") Integer id) {
        CrmInfoNumVO num = crmLeadsService.num(id);
        return R.ok(num);
    }

    @PostMapping("/star/{id}")
    @ApiOperation("线索标星")
    public Result star(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        crmLeadsService.star(id);
        return R.ok();
    }

    @PostMapping("/information/{id}")
    @ApiOperation("查询详情页信息")
    public Result<List<CrmModelFiledVO>> information(@PathVariable("id") @ApiParam(name = "id", value = "id") Integer id) {
        List<CrmModelFiledVO> information = crmLeadsService.information(id);
        return R.ok(information);
    }

    @PostMapping("/uploadExcel")
    @ApiOperation("导入线索")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_IMPORT,object = "导入线索",detail = "导入线索")
    public Result<Long> uploadExcel(@RequestParam("file") MultipartFile file, @RequestParam("ownerUserId") Long ownerUserId, @RequestParam("repeatHandling") Integer repeatHandling, @RequestParam("leadsUserId") Long leadsUserId) {
        UploadExcelBO uploadExcelBO = new UploadExcelBO();
        uploadExcelBO.setOwnerUserId(ownerUserId);
        uploadExcelBO.setLeadsUserId(leadsUserId);
        uploadExcelBO.setUserInfo(UserUtil.getUser());
        uploadExcelBO.setCrmEnum(CrmEnum.LEADS);
        uploadExcelBO.setPoolId(null);
        uploadExcelBO.setRepeatHandling(repeatHandling);
        Long messageId = uploadExcelService.uploadExcel(file, uploadExcelBO);
        return R.ok(messageId);
    }

    @PostMapping("/updateInformation")
    @ApiOperation("基本信息保存修改")
    @SysLogHandler(behavior = BehaviorEnum.UPDATE)
    public Result updateInformation(@RequestBody CrmUpdateInformationBO updateInformationBO) {
        crmLeadsService.updateInformation(updateInformationBO);
        return R.ok();
    }

    @PostMapping("/dataCheck")
    @ApiOperation("数据查重")
    public Result<List<CrmDataCheckVO>> dataCheck(@RequestBody CrmDataCheckBO dataCheckBO) {
        List<CrmDataCheckVO> crmDataCheckVOS = crmLeadsService.dataCheck(dataCheckBO);
        return Result.ok(crmDataCheckVOS);
    }

    @PostMapping("/queryClue")
    @ApiOperation("综合统计 线索业务")
    Result<BasePage<Map<String, Object>>> queryClue(int num, int start, int end, String year) {  //start = 开始期数   end = 结束期数
       //num   2/3=报课量   4/5=加好友量   8/9=成交量
        CrmSearchBO search = new CrmSearchBO();
        search.setSearch("");
        CrmSearchBO.Search obj = new CrmSearchBO.Search();
        CrmSearchBO.Search obj1 = new CrmSearchBO.Search();
        search.setPageType(1);
        search.getSearchList().add(0,obj);
        search.getSearchList().add(1,obj1);
            if (num == 2 || num == 3) {
                //报课量
                search.getSearchList().get(0).setName("signClass");
                search.getSearchList().get(0).setFormType("select");
                search.getSearchList().get(0).setSearchEnum(CrmSearchBO.FieldSearchEnum.IS);
                search.getSearchList().get(0).setScript(null);
                List<String> list = new ArrayList<>();
                list.add(0, "是");
                search.getSearchList().get(0).setValues(Collections.singletonList(list.get(0)));

            } else if (num == 4 || num == 5) {
                //加微信(好友)量
                search.getSearchList().get(0).setName("addWechat");
                search.getSearchList().get(0).setFormType("select");
                search.getSearchList().get(0).setSearchEnum(CrmSearchBO.FieldSearchEnum.IS);
                search.getSearchList().get(0).setScript(null);
                List<String> list = new ArrayList<>();
                list.add(0, "是");
                search.getSearchList().get(0).setValues(Collections.singletonList(list.get(0)));

            } else if (num == 8 || num == 9) {
                //成交量
                search.getSearchList().get(0).setName("vipDealStatus");
                search.getSearchList().get(0).setFormType("text");
                search.getSearchList().get(0).setSearchEnum(CrmSearchBO.FieldSearchEnum.IS);
                search.getSearchList().get(0).setScript(null);
                List<String> list = new ArrayList<>();
                list.add(0, "已成交");
                search.getSearchList().get(0).setValues(Collections.singletonList(list.get(0)));
            }

        if(start != -1 && end != -1) { //根据期数查询
            //训练营期数(start,end)
            search.getSearchList().get(1).setName("trainingPeriods");
            search.getSearchList().get(1).setFormType("number_input");
            search.getSearchList().get(1).setScript(null);
            search.getSearchList().get(1).setSearchEnum(CrmSearchBO.FieldSearchEnum.IS);
            int len = end - start + 1;
            int arrayNum[] = new int[len];
            for (int i = start, j = 0; i <= end; i++, j++) {
                //int j=1; j++;
                arrayNum[j] = i;
            }
            List<String> resList = new ArrayList<>();
            for (int n = 1, j = 0; n <= len; n++, j++) {
                resList.add(j, String.valueOf(arrayNum[j]));
            }
            search.getSearchList().get(1).setValues(resList);
        }else if(start == -1 & end == -1) {  //根据年份查询
            if (year != null) {
                //用户指定年份
                String startYear = year + "-01-01 00:00:00";
                String endYear = year + "-12-31 23:59:59";
                search.getSearchList().get(1).setName("createTime");
                search.getSearchList().get(1).setFormType("datetime");
                search.getSearchList().get(1).setSearchEnum(CrmSearchBO.FieldSearchEnum.DATE_TIME);
                List<String> yearList=new ArrayList<>();
                yearList.add(0,startYear);
                yearList.add(1,endYear);
                search.getSearchList().get(1).setValues(yearList);

            } else if (year == null) {
                    LocalDate today = LocalDate.now();
                    String oldDay = null;
                    for(long i = 1L;i < 12L; i++){
                        LocalDate localDate = today.minusMonths(i);
                        oldDay = localDate.toString().substring(0,7);
                }
                String endYear = today + " 23:59:59";
                String startYear = oldDay+ "-01 00:00:00";
                search.getSearchList().get(1).setName("createTime");
                search.getSearchList().get(1).setFormType("datetime");
                search.getSearchList().get(1).setSearchEnum(CrmSearchBO.FieldSearchEnum.DATE_TIME);
                List<String> yearList=new ArrayList<>();
                yearList.add(0,startYear);
                yearList.add(1,endYear);
                search.getSearchList().get(1).setValues(yearList);
            }
        }
        BasePage<Map<String, Object>> mapBasePage = crmLeadsService.queryPageList(search);
        return R.ok(mapBasePage);
    }
    @PostMapping("/queryTMKLeads")
    @ApiOperation("TMK统计线索(BI)")
    public Result<List<CrmTmkLeads>> queryTMKLeads (@RequestBody CrmRoiSearchBO search){
        if (StringUtils.isNotBlank(search.getCategoryStr())) {
            String[] categories = search.getCategoryStr().split(",");
            int[] array = Arrays.asList(categories).stream().mapToInt(Integer::parseInt).toArray();
            search.setCategorys(array);
        }
        List<CrmTmkLeads> tmkList = crmLeadsService.queryTMKLeads(search);
        return  R.ok(tmkList);
    }
    @PostMapping("/tmkExportExcel")
    @ApiOperation("TMK全部导出")
    @SysLogHandler(behavior = BehaviorEnum.EXCEL_EXPORT, object = "tmk导出", detail = "全部导出")
    public void tmkExportExcel(@RequestBody CrmRoiSearchBO search, HttpServletResponse response) {
        if (StringUtils.isNotBlank(search.getCategoryStr())) {
            String[] categories = search.getCategoryStr().split(",");
            int[] array = Arrays.asList(categories).stream().mapToInt(Integer::parseInt).toArray();
            search.setCategorys(array);
        }
        crmLeadsService.tmkExportExcel(response, search);
    }

}
